package com.sdk.scan.act

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import cn.oi.klittle.era.base.KBaseActivityManager
import cn.oi.klittle.era.utils.KStringUtils
import com.sdk.scan.utils.KDoubleBirdUtils
import com.sdk.scan.utils.KScanReader
import com.sdk.scan.utils.KScanUtils
import com.sdk.scan.utils.qibin.KScanWithQibinUtils
import com.sdk.scan.utils.qibin.dongji.KScanWithQibinUtils2
import com.sdk.scan.utils.qibin.urovo.KScanWithQibinUrovoUtils
import java.lang.Exception

/**
 * 集成扫描功能和 NFC读卡功能
 * Created by 彭治铭 on 2019/3/13.
 */
open class KScanActivity : KRfidActivity() {

    //fixme 是否开启扫描
    open fun isEnableScan(): Boolean {
        return true//默认开启
    }

    //新增一个方法，控制扫描回调开关。
    open fun isEnableScan2(): Boolean {
        return true//默认开启
    }

    /**
     * fixme 扫描回调（isEnableScan()开启了才会回调）；交给子类重写
     */
    open fun onScanResult(barcodeType: Byte, barcodeStr: String) {}

    private var onScanResult: ((barcodeType: Byte, barcodeStr: String) -> Unit)? = null

    private fun onScanResult(onScanResult: ((barcodeType: Byte, barcodeStr: String) -> Unit)? = null) {
        this.onScanResult = onScanResult
    }

    private var pBarcodeStr: String? = null//fixme 记录上传扫描结果。
    private var pBarcodeTime: Long = 0//fixme 记录上传扫描的时间

    private var isNewPdA_Alpas2 = false//是否为新版PDA
    private var isDoubleBird = false//是否为新版PDA
    var isNewPdA_Alpas3_qibin = false//是否为旗滨PDA
    var isNewPdA_Alpas3_qibin2 = false//是否为旗滨PDA
    var isNewPdA_Alpas3_qibin3 = false//是否为旗滨PDA
    var scanQibin: KScanWithQibinUtils = KScanWithQibinUtils();
    var scanQibin2: KScanWithQibinUtils2 = KScanWithQibinUtils2();
    var scanQibin3: KScanWithQibinUrovoUtils = KScanWithQibinUrovoUtils();
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            if (isEnableScan()) {
                //回调监听
                onScanResult { barcodeType, barcodeStr ->
                    if (isEnableScan2() && barcodeStr != null) {
//                        if (barcodeStr.equals(pBarcodeStr)) {
//                            KLoggerUtils.e("重复扫描间隔时间：\t" + (System.currentTimeMillis() - pBarcodeTime))
//                        }
                        if (barcodeStr.equals(pBarcodeStr) && (System.currentTimeMillis() - pBarcodeTime) <= 900) {//fixme 测试发现新版PDA两次连续扫描间距在203~361之间左右。
                            pBarcodeTime = System.currentTimeMillis()
                            return@onScanResult//fixme 防止相同的时间，重复扫描一个条码。
                        } else {
                            pBarcodeStr = barcodeStr
                            pBarcodeTime = System.currentTimeMillis()
                            onScanResult(barcodeType, barcodeStr)
                        }
                    }
                }
                //监听扫描
                if (isNewPdA_DoubleBird()) {
                    isDoubleBird = true
                    KDoubleBirdUtils.registerReceiver()
                    //旧版本扫描注册
                    KDoubleBirdUtils.onScanResult(onScanResult)//在finish和onpause里不对它进行回收了；防止没有反应。
                } else if (isNewPdA_Alpas()) {
                    isNewPdA_Alpas2 = true
                    //新版扫描注册
                    onResultReceiver()
                    //fixme 不管新旧，兼容一下老版本。防止部分设备，名字上是新设备名称，实际调用的是旧版本的扫描。
                    KScanUtils.registerReceiver()
                    //旧版本扫描注册
                    KScanUtils.onScanResult(onScanResult)//在finish和onpause里不对它进行回收了；防止没有反应。
                } else if (KScanWithQibinUtils.isPDA_Qibin()) {
                    isNewPdA_Alpas3_qibin = true;
                    ///fixme 旗滨的PDA(凯立);
                    scanQibin.onResultReceiver(this, onScanResult);
                } else if (KScanWithQibinUtils2.isPDA_Qibin2()) {
                    isNewPdA_Alpas3_qibin2 = true;
                    ///fixme 旗滨的PDA（东集）;
                    scanQibin2.onResultReceiver(this, onScanResult);
                } else if (KScanWithQibinUrovoUtils.isPDA_QibinUrovo()) {
                    isNewPdA_Alpas3_qibin3 = true;
                    ///fixme 旗滨的PDA,另一台PDA;
                    scanQibin3.onResultReceiver(this, onScanResult);
                } else {
                    isNewPdA_Alpas2 = false
                    isDoubleBird = false
                    isNewPdA_Alpas3_qibin = false;
                    KScanUtils.registerReceiver()
                    //旧版本扫描注册
                    KScanUtils.onScanResult(onScanResult)//在finish和onpause里不对它进行回收了；防止没有反应。
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onPause() {
        super.onPause()
        if (scanReader != null) {
            scanReader?.stopScan()//停止扫描(关闭扫描灯)
        }
    }

    override fun onResume() {
        super.onResume()
//        if (scanReader != null) {
//            scanReader?.startScan()//启动扫描（会开启扫描灯的）
//        }
        try {
            if (isEnableScan()) {
                //监听扫描
                if (isNewPdA_Alpas2) {
                    //新版扫描注册
                } else if (isNewPdA_Alpas3_qibin) {
                    //旗滨PDA（凯立）
                } else if (isNewPdA_Alpas3_qibin2) {
                    //旗滨PDA（东集）
                } else if (isNewPdA_Alpas3_qibin3) {
                    //旗滨PDA
                    if (KScanWithQibinUrovoUtils.isPDA_QibinUrovo()) {
                        isNewPdA_Alpas3_qibin3 = true;
                        ///fixme 旗滨的PDA,另一台PDA;
                        scanQibin3.onResultReceiver(this, onScanResult);
                    }
                } else {
                    if (isDoubleBird) {
                        KDoubleBirdUtils.onScanResult(onScanResult)
                    } else {
                        //旧版本扫描注册;fixme 重新赋值扫描回调函数。防止跳转下一个Activity后，回调被覆盖。
                        KScanUtils.onScanResult(onScanResult)//在finish和onpause里不对它进行回收了；防止没有反应。
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onStop() {
        super.onStop()
        if (KScanWithQibinUrovoUtils.isPDA_QibinUrovo()) {
            ///修复旗滨PDA并架跳转时，扫描没有回调的问题；（即第一个扫描页面跳转到第二个扫描页面时，第二个扫描页面接收不到扫描信息的问题）
            ///旗滨第二个扫描页面要想接收到扫描信息，前一个页面必须先注销到广播。不然始终只有第一个页面能接收；
            scanQibin3.unregisterReceiver(this);
        }
    }

    /**
     * 新版PDA扫描接收
     */
    private var scanReader: KScanReader? = null
    private var resultReceiver: BroadcastReceiver? = null
    private fun onResultReceiver() {
        try {
            if (isNewPdA_Alpas()) {
                if (scanReader == null) {
                    scanReader = KScanReader(this)
                    scanReader?.init()//初始扫描
                }
                if (resultReceiver == null) {
                    //接收返回数据
                    resultReceiver = object : BroadcastReceiver() {
                        override fun onReceive(context: Context, intent: Intent) {
                            try {
                                if (isFastScan()) {
                                    return//fixme 防止重复扫描
                                }
                                //fixme 只对当前Activity进行回调。
                                if (KBaseActivityManager.getInstance().stackTopActivity === getActivity()) {
                                    var barcode = intent.getByteArrayExtra(KScanReader.SCAN_RESULT)
                                    //Log.e("MainActivity", "barcode = " + String(barcode!!))
                                    if (barcode != null) {
                                        onScanResult?.let {
                                            it(0, KStringUtils.bytesToString(barcode).trim())
                                        }
                                    }
                                }
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                    var filter = IntentFilter()
                    filter.addAction(KScanReader.ACTION_SCAN_RESULT)
                    registerReceiver(resultReceiver, filter)//广播注册接收
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun finish() {
        super.finish()
        try {
            if (isNewPdA_Alpas()) {
                scanReader?.closeScan()//关闭扫描
                if (resultReceiver != null) {
                    unregisterReceiver(resultReceiver)
                    resultReceiver = null
                }
                scanReader = null
            }
            pBarcodeTime = 0
            pBarcodeStr = null
            if (KScanWithQibinUtils.isPDA_Qibin()) {
                ///fixme 旗滨的PDA（凯立）,必须取消注册广播。
                scanQibin.unregisterReceiver(this);
            }
            if (KScanWithQibinUtils2.isPDA_Qibin2()) {
                ///fixme 旗滨的PDA(东集),必须取消注册广播。
                scanQibin2.unregisterReceiver(this);
            }
            if (KScanWithQibinUrovoUtils.isPDA_QibinUrovo()) {
                scanQibin3.unregisterReceiver(this);
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    companion object {
        // 两次扫描之间的点击间隔不能少于200毫秒
        var MIN_CLICK_DELAY_TIME_scan: Long = 200
        var lastClickTime_scan = 0L//记录最后一次刷卡时间

        //判断是否超快速，重复扫描
        fun isFastScan(): Boolean {
            var flag = false
            val curClickTime = System.currentTimeMillis()
            if (curClickTime - lastClickTime_scan <= MIN_CLICK_DELAY_TIME_scan) {
                flag = true//快速点击
            }
            lastClickTime_scan = curClickTime
            return flag
        }
    }

}